<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        width="50%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }} -
                {{ adminInfo.currentStore.name }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <FormItem
                        :label="t('appointment.room_id')"
                        type="remoteSelect"
                        v-model="baTable.form.items!.room_id"
                        prop="room_id"
                        :input-attr="{ pk: 'room.id', field: 'name', remoteUrl: '/admin/Room/index' }"
                        :placeholder="t('Please select field', { field: t('appointment.room_id') })"
                    />
                    <FormItem
                        :label="t('appointment.medical_staff_id')"
                        type="remoteSelect"
                        v-model="baTable.form.items!.medical_staff_id"
                        prop="medical_staff_id"
                        :input-attr="{ pk: 'medical_staff.id', field: 'name', remoteUrl: '/admin/MedicalStaff/index' }"
                        :placeholder="t('Please select field', { field: t('appointment.medical_staff_id') })"
                    />

                    <el-form-item label="养生项目" prop="healthItemSelections">
                        <div style="margin-bottom: 15px">
                            <el-button type="primary" :icon="Plus" @click="addHealthItemSelection" size="small"> 添加项目 </el-button>
                        </div>
                        <div
                            v-for="(selection, index) in baTable.form.items!.healthItemSelections"
                            :key="index"
                            style="margin-bottom: 5px; width: 100%"
                        >
                            <div style="display: flex; align-items: center; width: 100%; gap: 10px">
                                <el-select
                                    v-model="selection.health_item_id"
                                    filterable
                                    remote
                                    reserve-keyword
                                    :remote-method="fetchHealthItems"
                                    :loading="healthItemPagination.loading"
                                    placeholder="请选择养生项目"
                                    style="flex: 1"
                                    @change="onHealthItemChange"
                                >
                                    <el-option
                                        v-for="(item, index) in healthItemOptions"
                                        :key="index"
                                        :label="item?.name || '未知项目'"
                                        :value="item?.id"
                                    >
                                        <span>{{ item?.name || '未知项目' }}</span>
                                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item?.duration || 0 }}分钟</span>
                                    </el-option>
                                    <template #footer>
                                        <el-pagination
                                            v-if="healthItemPagination.total > healthItemPagination.pageSize"
                                            size="small"
                                            layout="prev, pager, next"
                                            :total="healthItemPagination.total"
                                            :page-size="healthItemPagination.pageSize"
                                            :current-page="healthItemPagination.page"
                                            @current-change="handleHealthItemPageChange"
                                        />
                                    </template>
                                </el-select>
                                <el-button type="danger" :icon="Minus" @click="removeHealthItemSelection(index)" size="small" style="flex-shrink: 0">
                                    删除
                                </el-button>
                            </div>
                        </div>
                        <div v-if="totalHealthItemDuration > 0" class="total-duration" style="color: #409eff">
                            总时长: {{ totalHealthItemDuration }} 分钟
                        </div>
                    </el-form-item>
                    <el-form-item label="预约时间" required>
                        <div style="display: flex; gap: 10px; align-items: center">
                            <el-form-item prop="appointment_date" style="margin-bottom: 0">
                                <el-date-picker
                                    v-model="baTable.form.items!.appointment_date"
                                    type="date"
                                    placeholder="选择日期"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
                                    style="width: 120px"
                                />
                            </el-form-item>
                            <el-form-item prop="start_time" style="margin-bottom: 0">
                                <el-input
                                    v-model="baTable.form.items!.start_time"
                                    placeholder="开始时间 (如: 09:30)"
                                    @input="formatTimeInput"
                                    maxlength="5"
                                    style="width: 80px"
                                />
                            </el-form-item>
                        </div>
                    </el-form-item>
                    <!-- <el-time-select
                            v-model="baTable.form.items!.start_time"
                            :max-time="baTable.form.items?.end_time"
                            style="width: 150px"
                            placeholder="开始时间"
                            prop="start_time"
                            start="08:00"
                            step="00:05"
                            end="22:00"
                            format="HH:mm"
                            value-format="HH:mm"
                            :default-value="
                                baTable.form.items?.start_time
                                    ? new Date(baTable.form.items.start_time).toLocaleTimeString('zh-CN', {
                                          hour: '2-digit',
                                          minute: '2-digit',
                                          hour12: false,
                                      })
                                    : undefined
                            "
                        />
                        到
                        <el-time-select
                            v-model="baTable.form.items!.end_time"
                            :min-time="baTable.form.items?.start_time"
                            style="width: 150px"
                            placeholder="结束时间"
                            prop="end_time"
                            start="08:00"
                            step="00:05"
                            end="22:00"
                            format="HH:mm"
                            value-format="HH:mm"
                            :default-value="
                                baTable.form.items?.end_time
                                    ? new Date(baTable.form.items.end_time).toLocaleTimeString('zh-CN', {
                                          hour: '2-digit',
                                          minute: '2-digit',
                                          hour12: false,
                                      })
                                    : undefined
                            "
                        /> -->
                    <!-- <el-form-item label="选择时间" required>

                    </el-form-item> -->
                    <FormItem
                        :label="t('appointment.patient_name')"
                        v-model="baTable.form.items!.patient_name"
                        type="string"
                        prop="patient_name"
                        :placeholder="t('Please input field', { field: t('appointment.patient_name') })"
                    />
                    <el-form-item label="患者性别">
                        <el-radio-group v-model="baTable.form.items!.patient_gender">
                            <el-radio :value="1">男</el-radio>
                            <el-radio :value="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="手机号">
                        <el-input
                            v-model="baTable.form.items!.patient_phone"
                            maxlength="11"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            placeholder="请输入手机号"
                        />
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="baTable.form.items!.symptoms" type="textarea" />
                    </el-form-item>
                    <FormItem
                        :label="t('appointment.is_cancel')"
                        type="radio"
                        v-model="baTable.form.items!.is_cancel"
                        prop="is_cancel"
                        :input-attr="{ content: { '1': t('appointment.is_cancel 1'), '0': t('appointment.is_cancel 0') } }"
                        :placeholder="t('Please select field', { field: t('appointment.is_cancel') })"
                    />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="customSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormItemRule } from 'element-plus'
import { inject, reactive, useTemplateRef, watch, ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'
import type { FormInstance } from 'element-plus'
import { useAdminInfo } from '/@/stores/adminInfo'
import createAxios from '/@/utils/axios'
import dayjs from 'dayjs'

const adminInfo = useAdminInfo()
const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

// 养生项目相关数据
const healthItemOptions = ref<any[]>([])
const healthItemPagination = ref({
    page: 1,
    pageSize: 10,
    total: 0,
    loading: false,
})

// 计算总时长
const totalHealthItemDuration = computed(() => {
    if (!baTable.form.items?.healthItemSelections) return 0
    return baTable.form.items.healthItemSelections.reduce((total: number, selection: any) => {
        if (!Array.isArray(healthItemOptions.value)) {
            return total
        }
        const item = healthItemOptions.value.find((item) => item && item.id === selection.health_item_id)
        return total + (item ? item.duration || 0 : 0)
    }, 0)
})

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    room_id: [buildValidatorData({ name: 'required', title: t('appointment.room_id') })],
    medical_staff_id: [buildValidatorData({ name: 'required', title: t('appointment.medical_staff_id') })],
    appointment_date: [buildValidatorData({ name: 'required', title: '预约日期' })],
    patient_age: [buildValidatorData({ name: 'number', title: t('appointment.patient_age') })],
    start_time: [
        buildValidatorData({ name: 'required', title: t('appointment.start_time') }),
        {
            validator: (rule: any, value: string, callback: any) => {
                if (!value) {
                    callback()
                    return
                }

                // 检查时间格式是否为HH:mm
                const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
                if (!timeRegex.test(value)) {
                    callback(new Error('请输入正确的时间格式'))
                    return
                }

                // 检查输入长度，确保至少4位数字（不包括冒号）
                const digitsOnly = value.replace(':', '')
                if (digitsOnly.length < 4) {
                    callback(new Error('时间格式不完整'))
                    return
                }

                callback()
            },
            trigger: 'blur',
        },
    ],
    end_time: [buildValidatorData({ name: 'required', title: t('appointment.end_time') })],
    created_at: [buildValidatorData({ name: 'date', title: t('appointment.created_at') })],
    updated_at: [buildValidatorData({ name: 'date', title: t('appointment.updated_at') })],
    healthItemSelections: [
        {
            validator: (rule: any, value: any[], callback: any) => {
                if (!value || value.length === 0 || !value.some((item: any) => item.health_item_id)) {
                    callback(new Error('请至少选择一个养生项目'))
                    return
                }
                callback()
            },
            trigger: 'change',
        },
    ],
})

// 养生项目相关方法
function addHealthItemSelection() {
    if (!baTable.form.items?.healthItemSelections) {
        if (baTable.form.items) {
            baTable.form.items.healthItemSelections = []
        }
    }
    if (baTable.form.items?.healthItemSelections) {
        baTable.form.items.healthItemSelections.push({ health_item_id: undefined })
    }
}

function removeHealthItemSelection(index: number) {
    if (baTable.form.items?.healthItemSelections && baTable.form.items.healthItemSelections.length > 0) {
        baTable.form.items.healthItemSelections.splice(index, 1)
        updateEndTime()
    }
}

function onHealthItemChange() {
    updateEndTime()
}

// 远程搜索养生项目
function fetchHealthItems(query: string) {
    healthItemPagination.value.loading = true
    createAxios({
        url: '/admin/HealthItems/index',
        method: 'get',
        params: {
            quickSearch: query,
            page: healthItemPagination.value.page,
            limit: healthItemPagination.value.pageSize,
        },
    })
        .then((res: any) => {
            if (res.code === 1) {
                healthItemOptions.value = res.data.list || []
                healthItemPagination.value.total = res.data.total || 0
            }
            healthItemPagination.value.loading = false
        })
        .catch((error) => {
            console.error('获取养生项目失败:', error)
            healthItemOptions.value = []
            healthItemPagination.value.loading = false
        })
}

// 养生项目分页变化
function handleHealthItemPageChange(page: number) {
    healthItemPagination.value.page = page
    fetchHealthItems('')
}

// 统一的时间输入格式化函数
function formatTimeValue(value: string): string {
    if (!value) {
        return ''
    }

    // 移除所有非数字字符
    let cleanValue = value.replace(/\D/g, '')

    // 限制最大长度为4位数字
    if (cleanValue.length > 4) {
        cleanValue = cleanValue.slice(0, 4)
    }

    // 只有在输入长度为2位或4位时才进行格式化
    if (cleanValue.length === 2) {
        // 验证小时数（00-23）
        let validHours = parseInt(cleanValue) || 0
        if (validHours > 23) {
            validHours = 23
        }
        return String(validHours).padStart(2, '0')
    } else if (cleanValue.length === 4) {
        const hours = cleanValue.slice(0, 2)
        const minutes = cleanValue.slice(2, 4)

        // 验证小时数（00-23）
        let validHours = parseInt(hours) || 0
        if (validHours > 23) {
            validHours = 23
        }

        // 验证分钟数（00-59）
        let validMinutes = parseInt(minutes) || 0
        if (validMinutes > 59) {
            validMinutes = 59
        }

        return `${String(validHours).padStart(2, '0')}:${String(validMinutes).padStart(2, '0')}`
    }

    // 其他情况直接返回原值（1位或3位数字）
    return cleanValue
}

// 时间输入格式化
function formatTimeInput(value: string) {
    const formattedValue = formatTimeValue(value)
    if (baTable.form.items) {
        baTable.form.items.start_time = formattedValue
        updateEndTime()
    }
}

// 更新结束时间
function updateEndTime() {
    if (baTable.form.items?.start_time && totalHealthItemDuration.value > 0) {
        const startTime = dayjs(`2000-01-01 ${baTable.form.items.start_time}`)
        const endTime = startTime.add(totalHealthItemDuration.value, 'minute')
        baTable.form.items.end_time = endTime.format('HH:mm')
    }
}

// 处理health_items数据的函数
const processHealthItemsData = (healthItems: any[]) => {
    if (healthItems && healthItems.length > 0) {
        // 转换为healthItemSelections格式
        baTable.form.items!.healthItemSelections = healthItems.map((item: any) => ({
            health_item_id: item.health_item_id,
            health_item_name: item.name,
            duration: item.duration || 0,
        }))

        // 更新healthItemOptions以确保下拉框正确显示
        const existingIds = healthItemOptions.value.map((option) => option.id)
        healthItems.forEach((item: any) => {
            if (!existingIds.includes(item.health_item_id)) {
                healthItemOptions.value.push({
                    id: item.health_item_id,
                    name: item.name,
                    duration: item.duration || 0,
                    description: item.description || '',
                })
            }
        })

        // 清除health_items字段，避免重复处理
        delete baTable.form.items!.health_items
    }
}

// 监听表单项变化，处理时间格式化
watch(
    () => baTable.form.items,
    (newVal) => {
        if (!newVal) return
        if (newVal.start_time) {
            newVal.start_time = dayjs(newVal.start_time).format('HH:mm')
        }
        // if (newVal.end_time) {
        //     newVal.end_time = formatTimeValue(newVal.end_time)
        // }

        // 处理养生项目数据
        if (newVal.health_items && Array.isArray(newVal.health_items) && newVal.health_items.length > 0) {
            processHealthItemsData(newVal.health_items)
        } else if (!newVal.healthItemSelections || !Array.isArray(newVal.healthItemSelections)) {
            // 如果没有养生项目选择，初始化为空数组
            newVal.healthItemSelections = []
        }
    }
    // { immediate: false, deep: false }
)

// 自定义提交方法，用于处理日期和时间的拼接
const customSubmit = (formRef?: FormInstance | null) => {
    if (!formRef) return

    formRef.validate((valid: boolean, fields?: any) => {
        if (!valid) {
            // 如果验证失败，显示第一个错误信息
            if (fields) {
                const firstError = Object.values(fields)[0] as any[]
                if (firstError && firstError[0] && firstError[0].message) {
                    ElMessage.error(firstError[0].message)
                }
            }
            return
        }

        if (baTable.form.items) {
            const appointmentDate = baTable.form.items.appointment_date
            const startTime = baTable.form.items.start_time
            const endTime = baTable.form.items.end_time

            if (!appointmentDate || !startTime) {
                ElMessage.error('请填写预约日期和开始时间')
                return
            }

            // 如果没有选择养生项目，提示用户
            if (
                !baTable.form.items.healthItemSelections ||
                baTable.form.items.healthItemSelections.length === 0 ||
                !baTable.form.items.healthItemSelections.some((item: any) => item.health_item_id)
            ) {
                ElMessage.error('请至少选择一个养生项目')
                return
            }

            // 调用原始提交方法
            baTable.onSubmit(formRef)
        }
    })
}
</script>

<style scoped lang="scss"></style>
